import random,redis,time
from datetime import datetime
from model.models import db

from flask import Blueprint, request, jsonify,send_file
from flask_restful import Api, Resource,reqparse
from captcha.image import ImageCaptcha
from utils.myredis import r
from utils.sms import send_message
from utils.myjwt import myjwt
from model.models import User

user_dp = Blueprint('user_dp', __name__)

api = Api(user_dp)

class ImgCode(Resource):
    def get(self,uuid):
        if not uuid:
            return jsonify({"code":400,"msg":"没有参数"})
        #生成图片验证码
        code = random.randint(1000,9999)
        img = ImageCaptcha()
        img_byte = img.generate(str(code))
        #存到redis
        key = "code_%s" % uuid
        r.set_str(key,code,time=300)
        return send_file(img_byte,"png")

api.add_resource(ImgCode,"/imgcode/<uuid>")


class SmsCode(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument("mobile")
        req.add_argument("imagecode")
        req.add_argument("uuid")
        args = req.parse_args()
        mobile = args["mobile"]
        imagecode = args["imagecode"]
        uuid = args["uuid"]
        if not mobile:
            return jsonify({"code":400,"msg":"参数没有"})
        key = "code_%s" % uuid
        code = r.get_str(key)
        if not code:
            return jsonify({"code":400,"msg":"图片验证码以过期"})
        print(code,imagecode)
        if code != imagecode:
            return jsonify({"code":400,"msg":"图片验证码错误"})

        code = random.randint(1000,9999)
        send_message(mobile,code)
        key = "sms_%s" % mobile
        r.set_str(key,code,60)
        return jsonify({"code":200,"msg":"获取成功"})

api.add_resource(SmsCode,"/sendsms")


class Login(Resource):
    def post(self):
        data = reqparse.RequestParser()
        data.add_argument("mobile")
        data.add_argument("code")
        args = data.parse_args()
        mobile = args["mobile"]
        code = args["code"]
        if not all([mobile,code]):
            return jsonify({"code":400,"msg":"参数没有"})
        #校验验证码
        key = "sms_%s" % mobile
        recode = r.get_str(key)
        print(">>",recode)
        if not recode:
            return jsonify({"code":400,"msg":"验证码过期"})
        if code != recode:
            return jsonify({"code":400,"msg":"验证码错误"})
        user_info = User.query.filter(User.mobile == mobile).first()
        if user_info:
            #用户存在直接登录
            data = {"data":{"userid":user_info.id,"mobile":user_info.mobile,"exptime":int(time.time())}}
            token = myjwt.jwt_encode(data)
            return jsonify({"code":200,"msg":"登录成功","token":token,"userid":user_info.id})
        if not user_info:
            #没有用户进行注册
            user = User(mobile=mobile)
            db.session.add(user)
            db.session.commit()
            data = {"data":{"userid":user_info.id,"mobile":user_info.mobile,"exptime":int(time.time())}}
            token = myjwt.jwt_encode(data)
            return jsonify({"code":200,"msg":"注册成功并登录","token":token,"userid":user_info.id})

api.add_resource(Login,"/login")